const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database({
	throwOnNotFound: false
})
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()

	let appoint = await db.collection('appoint').doc(event._id).field({
		appoint_date: false,
		openid: false
	}).get()
	if (!appoint.data) {
		return {
			code: 20008,
			msg: '预约记录不存在'
		}
	}
	appoint = appoint.data
	let staff = await db.collection('staff').field({
		group_id: true,
		rule_appoints: true
	}).where({
		_openid: wxContext.OPENID,
		shop_id: appoint.shop_id,
	}).get()
	if (staff.data.length == 0) {
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	staff = staff.data[0]

	if (staff.group_id == 3 || (staff.group_id == 2 && !staff.rule_appoints)) {
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	if (event.op == 'use') {
		if (appoint.status == 2 || appoint.status == 5) {
			await db.collection('appoint').doc(event._id).update({
				data: {
					status: 7,
					use_time: new Date()
				}
			})
			appoint.status = 7
			appoint.use_time = new Date()
		}else{
			return {
				code: 20009,
				msg: '当前状态无法进行此操作'
			}
		}
	} else if (event.op == 'cancel') {
		if (appoint.status == 1 || appoint.status == 2) {
			await db.collection('appoint').doc(event._id).update({
				data: {
					status: 6,
					cancel_time: new Date()
				}
			})
			appoint.status = 6
			appoint.cancel_time = new Date()
		}else{
			return {
				code: 20009,
				msg: '当前状态无法进行此操作'
			}
		}
	}
	let timeline = (await db.collection('timeline').doc(appoint.timeline_id).field({
		time_begin: true,
		time_end: true
	}).get()).data
	let daily = (await db.collection('daily').doc(appoint.daily_id).field({
		date: true,
		time_result: true
	}).get()).data
	let product = (await db.collection('product').doc(appoint.product_id).field({
		name: true,
	}).get()).data


	return {
		code: 200,
		msg: '操作成功',
		data: {
			timeline,
			daily,
			product,
			appoint
		}
	}
}